package org.bim.view.drag.design.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.bim.view.drag.design.api.vo.TUserVO;
import org.bim.view.drag.design.entity.BaseEntity;
import org.bim.view.drag.design.util.ThreadLocalUtil;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Properties;


/**
 * 添加时间注解拦截器,通过拦截sql，自动给带注解的属性添加时间
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public  class ModelFillInterceptor implements Interceptor {
    protected  String setOperator(){
       TUserVO vo = ThreadLocalUtil.getCurrentUser();
       if(vo!=null){
           return vo.getAccount();
       }
      return "admin";
    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        // 获取 SQL 类型
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();

        if (!SqlCommandType.INSERT.equals(sqlCommandType) && !SqlCommandType.UPDATE.equals(sqlCommandType)) {
            return invocation.proceed();
        }
        // 获取参数
        Object parameter = invocation.getArgs()[1];
        if (parameter == null) {
            return invocation.proceed();
        }
        if (parameter instanceof BaseEntity) {
            BaseEntity entity = (BaseEntity) parameter;
            if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                entity.setCreateTime(new Date());
                entity.setUpdateTime(new Date());
                entity.setCreateUser(setOperator());
                entity.setUpdateUser(setOperator());
            } else {
                entity.setUpdateTime(new Date());
                entity.setUpdateUser(setOperator());
            }
        }
        return invocation.proceed();
    }


    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        log.debug("设置填充字段mapper的参数，{}", properties.toString());
    }
}
